package com.mengjian.myspringai.mcpserver;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.mcp.McpToolUtils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

/**
 * @author xieren
 * created by 2025/7/2
 */

@Service
@Slf4j
public class WeatherMcp {
    @Resource
    private HttpClient httpClient;
    private final String apiKey = "SgnzRvy9tZQZ_5FLJ";

    @Tool(description = "根据城市名获取该城市的天气信息实况")
    public String getWeatherByCityName(@ToolParam(description = "城市名称") String cityName, ToolContext toolContext) {
        Map<String, Object> context = toolContext.getContext();
        log.info(context.toString());
        System.out.println("获取城市天气信息：" + cityName);
        String nowUrl = "https://api.seniverse.com/v3/weather/now.json?key=" + apiKey + "&location=";
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(nowUrl + cityName))
                .build();
        try {
            var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("获取城市天气信息成功：" + response.body());
            return response.body();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "获取天气信息失败";
        }
    }
    @Tool(description = "获取某个城市未来几天的天气")
    public String getWeatherForecastByCityName(@ToolParam(description = "城市名称") String cityName,
                                               @ToolParam(description = "从第几天开始算，0代表今天") Integer startDay,
                                               @ToolParam(description = "要查询的天数，2代表两天") Integer days) {
        System.out.println("获取城市天气信息：" + cityName);
        String forecastUrl = "https://api.seniverse.com/v3/weather/daily.json?key=" + apiKey + "&location=" + cityName + "&start=" + startDay + "&days=" + days;
        System.out.println(forecastUrl);
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(forecastUrl))
                .build();
        try {
            var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println("获取城市天气信息成功：" + response.body());
            return response.body();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "获取天气信息失败";
        }
    }


}
